#include <pthread.h>
#include "app_common.h" 
#include "stdio.h"
#include <stdlib.h>


int  calc_square( int num)
{
     //假设此处有耗时计算  
     sleep(1);
     int result= num*num;
     return result;
}

void *calc_square_thread(void *num)
{
    sleep(1);
    // 从参数中取值 进行平方运算 返回结果
    //1 强转
    int *num_p=(int *)num;
    int  num_int= *num_p ; //解引用
   //  int result= num_int*num_int; //计算 错 
   int *result = malloc(sizeof(int));
    *result=num_int*num_int;
    return  (void *)result; //返回
}



// 求：计算一组数字的平方值并进行累加。
int main(int argc, char const *argv[])
{
    int nums[]={1,2,3,4,5};
    int sum=0;
    int result[5];
    long start_ms=  app_common_getCurTimeMs();
    pthread_t pthreads[5];

    for (int i = 0; i < 5; i++)
    {
       // result[i]= calc_square(nums[i]);
        pthread_create(&pthreads[i],NULL,calc_square_thread,&nums[i]);
        
    }

    for (int i = 0; i < 5; i++)
    {   
        void *result_p;
        pthread_join(pthreads[i], &result_p );

        int *result_int_p=  (int *)result_p;
        int result_int=  *result_int_p;
        result[i]=result_int;
    }

    
    for (int i = 0; i < 5; i++)
    {
       // sleep(1);
        sum+=result[i];
    }
    printf("time=%ld\n",app_common_getCurTimeMs()-start_ms);
    printf("sum=%d\n",sum);

    return 0;
}
